import { EventBus } from '@/store/index'
import { mapActions, mapState, mapGetters } from 'vuex'
import { reactive } from 'vue'
import { isJSON, isHasOwnProperty, getCompIdByParam } from '@/plugins/utils'
import { COMPONENT_TYPES, CONTROL_TYPES, PAGE_TYPE } from '@/common/const'
import { ANIMATE_TRIGGER_TYPE_MAP } from '@/common/const-animates'
import { MOBILE_WID_HEI } from '@/common/const-dif'
export const template = {
  props: {
    pageId: {
      type: Number,
      default: -1,
    },
    popId: {
      type: Number,
      default: -1,
    },
    //可以通过e.stopPropagation()来阻止事件冒泡到这里来，也可以设置isPropagation值来阻止事件的触发
    isPropagation: {
      type: Boolean,
      default: true,
    },
    isHiddenComp: {
      type: Boolean,
      default: false,
    },
  },
  created() {
    //在web端，是页面都返回
    if(this.isH5Edit || !this.item || !this.item.commonAttr || !this.item.id) {
      return
    }else if(this.item && this.item.components && this.item.components.length > 0) {
      return
    }
    if(this.item.animate && this.item.animate.animates.length > 0) {
      if(this.siteAttrs.pageType == PAGE_TYPE.long) {
        this.isScrollAnimateClass = true;
      }
      this.isCssAnimateClass = true;
    }
    if(this.initEventsFun){
      this.initEventsFun()
    }
    if(this.onInitEvent){
      this.onInitEvent();
    }
    if(_.size(this.loadEvents) > 0){
      EventBus.$off("reloadLoad", this.onReloadLoad)
      EventBus.$on("reloadLoad", this.onReloadLoad)
      if(this.popId > 0) {
        this.$store.commit("updatePopReloadData", true);
      } else {
        this.$store.commit("updateReloadData", true);
      }
    }
    EventBus.$off("reloadInit", this.onReloadInit)
    EventBus.$on("reloadInit", this.onReloadInit)

    EventBus.$off("itemClick", this.onItemPropagationClick)
    EventBus.$on("itemClick", this.onItemPropagationClick)

    EventBus.$off("postInitEvent", this.onPostInitEvent)
    EventBus.$on("postInitEvent", this.onPostInitEvent)


    if(this.item.cid == COMPONENT_TYPES.wb_slot_machine){
      EventBus.$off("delayShowPostPop", this.onDelayShowPostPop)
      EventBus.$on("delayShowPostPop", this.onDelayShowPostPop)
    }


    if(this.item.events.submit){
      EventBus.$off("wbSubmitCallback", this.onContinueEvents)
      EventBus.$on("wbSubmitCallback", this.onContinueEvents)
      EventBus.$off("resetSubmitStatus", this.onResetSubmitStatus)
      EventBus.$on("resetSubmitStatus", this.onResetSubmitStatus)
    }


    EventBus.$off("playCssAnimate", this.playCssAnimate)
    EventBus.$on("playCssAnimate", this.playCssAnimate)
  },
  computed: {
    ...mapState({
      clickStatics: state => state.user.clickStatics,
      isDisplayClickStatics: state => state.user.isDisplayClickStatics,
    }),
    ...mapGetters({
      isSwiper: "isSwiper",
    }),
    commonAttr() {
      return this.item.commonAttr
    },
    isNotRelateCompId(){
      let numberData = this.getItemControls && this.getItemControls[CONTROL_TYPES.number]
      if(numberData && numberData.data.syn_com_id && numberData.data.syn_com_id.length > 0){
        return false
      }else{
        return true
      }
    },
    isDisplayVoteOrNumberBtn(){
      let text = this.commonAttr.text;
      let attrName = this.getAttrNameByParam(text);
      if(this.item.cid == COMPONENT_TYPES.wb_text && attrName && attrName.length > 0){
        return false;
      }else{
        return true;
      }
    },
    getTemplateClass(){
      let classes = [{
        'isHiddenComp': !this.commonAttr.isVisible,
        'scroll-animate': this.isScrollAnimateClass,
        'css-animate': this.isCssAnimateClass,
        'component-gsap': this.item.animate && this.item.animate.isGsap && this.item.animate.triggerType == ANIMATE_TRIGGER_TYPE_MAP.auto,
      }];

      if(this.commonAttr.groupAnimateClass){
        classes.push(this.commonAttr.groupAnimateClass);
      }
      //添加组件在打组组件中写入的class index-page-data dealGroupScrollTriggerAnimate.js
      if(this.commonAttr.scrollTrigger && this.commonAttr.scrollTrigger.scrollTriggerClasses){
        classes = _.concat(classes, this.commonAttr.scrollTrigger.scrollTriggerClasses);
      }
      return classes;
    },
  },
  mounted() {
    if(this.item && this.item.animate && this.item.animate.animates.length > 0) {
      if(!this.isH5Edit){
        this.loadImgPlayAnimate();
      }else{
        this.addAnimateListener()
      }
    }
  },
  methods: {
    ...mapActions({
      updateAnimateByIndex: "components/updateAnimateByIndex",
      updateActivityInfo: "updateActivityInfo",
    }),
    addAnimateListener() {
      this.addAnimateEvent();
      EventBus.$off("playAnimate", this.onPlayAnimate)
      EventBus.$on("playAnimate", this.onPlayAnimate)
    },
    removeAnimateListener() {
      EventBus.$off("playAnimate", this.onPlayAnimate)
      this.$el.removeEventListener("animationend", this.clearAnimates);
      this.$el.removeEventListener("webkitAnimationEnd", this.clearAnimates);
    },
    onPlayAnimate() {
      this.addAnimReactiveData();
      this.addAnimateEvent();
      this.playAnimate();
    },
    addAnimReactiveData() {
      if(!isHasOwnProperty(this.animateStyle, "opacity")) {
        this.animateStyle = reactive({
          animationName: "",
          animationDuration: 0,
          animationDelay: 0,
          animationIterationCount: 0,
          animationPlayState: "paused",
        })
      }
    },
    loadImgPlayAnimate(){
      if(this.item.animate.triggerType == ANIMATE_TRIGGER_TYPE_MAP.click){
        return;
      }
      this.addAnimReactiveData();
      this.addAnimateEvent();
      if(this.item.cid == COMPONENT_TYPES.wb_img){
        this.loadImgCb = window.setInterval(() => {
          if(this.item.commonAttr.isLoadedImg){
            window.clearInterval(this.loadImgCb);
            this.playAnimate();
          }
        }, this.siteInfo.reloadTime)
      }else{
        this.playAnimate();
      }
    },
    playAnimateOrGsap(e){
      if(this.item.animate.isGsap){
        if(this.item.commonAttr.isSelected_){
          this.playCompGsap();
        }else{
          this.pauseCompGsap();
        }
      }else{
        this.playAnimate();
      }
      this.isPostWbEventOrCommonEvents({ loadEvent: null, e })
    },
    playCompGsap(){
      if(this.gsap_){
        this.gsap_.restart();
        this.gsap_.play();
      }else{
        const componentData = this.item;
        const gsapOptionStr = componentData.animate.gsap.options;
        if(gsapOptionStr && isJSON(gsapOptionStr)){
          const gsapAttr = componentData.animate.gsap;
          let gsapOptions = JSON.parse(gsapOptionStr);

          gsapOptions.duration = parseFloat(gsapAttr.durations);
          gsapOptions.ease = gsapAttr.ease;
          gsapOptions.yoyo = gsapAttr.yoyo;
          gsapOptions.repeat = parseFloat(gsapAttr.repeat);

          this.gsap_ = window.gsap.to(this.$el, gsapOptions);
        }else if(componentData.animate.isPathAnimate){
          // 点击的时候实现高级动画内容 设置了路径的
          const path = componentData.animate.path
          const gsapAttr = componentData.animate.gsap;
          const attrs = JSON.parse(path.attrs);
          const repeat = parseInt(gsapAttr.repeat);
          const durations = gsapAttr.durations.split(",");
          const defaultDuration = parseInt(durations[0]);
          const conAttr = componentData.commonAttr
          let ease = 'power3.inOut';
          if(gsapAttr.ease){
            if(gsapAttr.ease === 'none'){
              ease = gsapAttr.ease;
            }else{
              ease = gsapAttr.ease + '.' + gsapAttr.easeInOut;
            }
          }

          let tl = gsap.timeline({
            repeat: repeat,
            yoyo: gsapAttr.yoyo,
            defaults: { duration: defaultDuration, ease: ease },
            onComplete: () => {
              if(gsapAttr.isOnComplete){
                EventBus.$emit("itemClick", {id: componentData.id, index: -1})
              }
            }
          });
          _.forEach(attrs, (attr, index) => {
            const duration = parseInt(durations[index]);
            const xx = Math.abs(attr.x - conAttr.left) < 5 ? 0 : attr.x/MOBILE_WID_HEI.adaptiveScale;
            const yy = componentData.isInGroup || Math.abs(attr.y - conAttr.top) < 5 ? 0 : attr.y/MOBILE_WID_HEI.adaptiveScale;
            tl.to(this.$el, {
              duration: duration ? duration : defaultDuration,
              alpha: isHasOwnProperty(attr, 'alpha') ? attr.alpha : 1,
              scale: isHasOwnProperty(attr, 'scale') ? attr.scale : 1,
              rotate: isHasOwnProperty(attr, 'rotate') ? attr.rotate : 0,
              x: parseInt(xx),
              y: parseInt(yy),
            });
          })
        }
      }
    },
    pauseCompGsap(){
      if(this.gsap_){
        this.gsap_.pause();
      }
    },
    playCssAnimate({ id }) {
      if(this.item.id == id){
        this.playAnimate()
      }
    },
    playAnimate() {
      this.clearIndex = 0;
      let index = this.item.animate.playAnimateIndex;
      if (this.item.animate.isPlayAll) {
        let animateStyle = this.animateStyle;
        let animationName = "";
        _.forEach(this.item.animate.animates, (item, index) => {
          if(index == 0) {
            this.setAniData(item);
            animationName = item.classStr;
          }else {
            animateStyle.opacity = item.opacity;
            animationName += "," + item.classStr;
            animateStyle.animationName = animationName;
            animateStyle.animationDuration += "," + item.duration + 's';
            animateStyle.animationDelay += "," + item.delay + 's';
            let repeat = item.repeat
            if(repeat >= 99){
              repeat = "infinite"
            }
            animateStyle.animationIterationCount += "," + repeat;
            animateStyle.animationPlayState = "";
          }
        });
        //:data-animate-name="animateStyle.animationName"
        if(this.$refs.injectTemplate && animationName){
          this.$refs.injectTemplate.setAttribute('data-animate-name', animationName);
        }
      } else if (index >= 0) {
        let item = this.item.animate.animates[index];
        if (item && item.isPlaying) {
          this.setAniData(item);
          let animateStyle = this.animateStyle;
          animateStyle.animationName = item.classStr;
          animateStyle.animationPlayState = item.isPlaying ? "" : "paused";
        } else {
          this.resetAniStatus();
        }
      } else {
        this.resetAniStatus();
      }
    },
    resetAniStatus(){
      if(this.item.animate){
        let aniLen = this.item.animate.animates.length;
        if(aniLen > 0 && this.clearIndex >= aniLen) {
          let animateStyle = this.animateStyle;
          animateStyle.opacity = 1;
          animateStyle.animationName = "";
          animateStyle.animationDuration = "";
          animateStyle.animationDelay = "";
          animateStyle.animationIterationCount = "";
          animateStyle.animationPlayState = "paused";
          // animateStyle.visibility = "visible";
          this.clearIndex = -1;
        }
      }
    },
    setAniData(item){
      let repeat = item.repeat
      if(repeat >= 99){
        repeat = "infinite"
      }
      let animateStyle = this.animateStyle;
      animateStyle.opacity = item.opacity;
      animateStyle.animationName = item.classStr;
      animateStyle.animationDuration = item.duration + 's';
      animateStyle.animationDelay = item.delay + 's';
      animateStyle.animationIterationCount = repeat;
      animateStyle.animationPlayState = "";
    },
    onResetSubmitStatus(){
      this.resetSubmitStatus()
    },
    onTemplateClick(e) {
      e.stopPropagation();
      if(this.isH5Edit || !this.isClick){
        return
      }
      if(this.isPropagation){
        let jumpUrl = "click"
        let comType = "click"
        let wModule = "click"
        this.onPostStatics(e, { comType, wModule,  jumpUrl })

        //前端点击事件关联组件，直接触发关联组件事件
        let relateEventCompId = getCompIdByParam(this.commonAttr.relateEventCompId);
        if(relateEventCompId && relateEventCompId.length > 0){
          this.relateCompEvent(relateEventCompId, e);
        }else{
          this.onEvent(e);
        }
      }
    },
    relateCompEvent(relateEventCompId, e){
      let itemIndex = parseInt(this.commonAttr.itemIndex);
      EventBus.$emit("itemClick", {id: relateEventCompId, index: itemIndex, e, isReset: false});
      window.setTimeout( () => {
        this.onEvent(e);
      }, 50);
    },
    onItemPropagationClick({id, index, isPost, e, isReset = true}){
      //如果关联组件是btn那么刷新按钮状态
      // if(this.item.cid == COMPONENT_TYPES.wb_btn){
      //   EventBus.$emit("btnStatus", { isSelected: true, compId: this.item.id });
      // }
      if(this.item.id == id){
        this.commonAttr.itemIndex = index
        if(isReset){
          this.resetSubmitStatus()
        }
        if(isPost){
          this.isPostWbEventOrCommonEvents({ loadEvent: null,  e })
        }else{
          this.onEvent(e)
        }
      }
    },
    clearAnimates() {
      if (this.isH5Edit) {
        let params = { index: this.item.animate.playAnimateIndex, item: { isPlaying: false } }
        this.updateAnimateByIndex(params);
      }
      this.clearIndex++;
      if(this.item.animate){
        this.resetAniStatus();
        if(!this.isH5Edit && this.item.events.animate){
          this.isPostWbEventOrCommonEvents({ loadEvent: null, e: null })
        }
      }
    },
    addAnimateEvent(){
      this.$el.removeEventListener("animationend", this.clearAnimates);
      this.$el.removeEventListener("webkitAnimationEnd", this.clearAnimates);
      this.$el.addEventListener("animationend", this.clearAnimates);
      this.$el.addEventListener("webkitAnimationEnd", this.clearAnimates);
    },
    onContinueEvents({e, compId}){
      if(compId == this.item.id){
        let pageIndex_ = this.pageId - 1
        if(pageIndex_ < 0){
          pageIndex_ = 0
        }
        if(this.statePopId > 0 && this.popId == this.statePopId || this.statePopId <= 0 && this.pageIndex == pageIndex_){
          if(this.wbEvents[this.eventIndex]){
            this.postWbEvent({e})
          }else{
            this.onFrontEvents(e)
          }
        }
      }
    },
    popArr(arr){
      while(arr && arr.length > 0){
        arr.pop();
      }
    },
    loadedImgs(compData, isAddNum){
      if(compData.components && compData.components.length > 0){
        _.forEach(compData.components, (compData_) => {
          this.loadedImgs(compData_, isAddNum);
        })
      }else if(compData.cid == COMPONENT_TYPES.wb_img || compData.cid == COMPONENT_TYPES.wb_head && compData.dataKeys.pic_url || compData.cid == COMPONENT_TYPES.wb_common_list){
        if(isAddNum){
          if(compData.cid == COMPONENT_TYPES.wb_img){
            if(compData.commonAttr.url){
              this.loadImgNum++;
            }
          }else{
            this.loadImgNum++;
          }
        }
        if(isHasOwnProperty(compData.commonAttr, "isLoadedImg") && compData.commonAttr.isLoadedImg){
          this.loadedImgNum++;
        }
      }
    },
    onPostInitEvent(){
      this.onInitEvent();
    },
  },
  watch: {
    isPropagation(val){
      this.isPropagation = val
    },
  },
  beforeUnmount(){
    EventBus.$off("playAnimate", this.onPlayAnimate)
    if(this.gsap_){
      window.gsap.killTweensOf(this.item.vueContainer.$el);
      this.item.vueContainer = null;
    }
    if(this.item){
      EventBus.$off("postInitEvent", this.onPostInitEvent)
      if(this.item.cid == COMPONENT_TYPES.wb_slot_machine){
        EventBus.$off("delayShowPostPop", this.onDelayShowPostPop)
      }

      EventBus.$off("itemClick", this.onItemPropagationClick);
      this.resetAniStatus();
      if(this.item.animate && this.item.animate.animates.length.length > 0){
        this.$el.removeEventListener("animationend", this.clearAnimates);
        this.$el.removeEventListener("webkitAnimationEnd", this.clearAnimates);
      }
      if(this.item.events){
        if(_.size(this.loadEvents) > 0){
          EventBus.$off("reloadLoad", this.onReloadLoad)
        }
        EventBus.$off("reloadInit", this.onReloadInit)

        if(this.item.events.submit){
          EventBus.$off("wbSubmitCallback", this.onContinueEvents);
          EventBus.$off("resetSubmitStatus", this.onResetSubmitStatus);
        }
        EventBus.$off("playCssAnimate", this.playCssAnimate)

        this.popArr(this.initEvents);
        this.popArr(this.loadEvents);
        this.popArr(this.commonFrontEvents);
        this.popArr(this.commonEvents);
      }
    }
  }
}
